package com.fc.hkx.shiro.realm;

import com.fc.hkx.entity.SysUserEntity;
import com.fc.hkx.service.ISysMenuService;
import com.fc.hkx.service.ISysRoleService;
import com.fc.hkx.service.ISysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Set;

/**
 * Created by Sunny on 2017-08-24.
 */
public class SysUserRealm extends AuthorizingRealm {

    private ISysUserService sysUserService;
    private ISysMenuService sysMenuService;
    private ISysRoleService sysRoleService;

    /**
     * 授权，验证权限时调用
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection)
    {
        SysUserEntity user = (SysUserEntity)principalCollection.getPrimaryPrincipal();
        Long userId = user.getUserId();

        //用户角色列表
        Set<String> roleSet  = sysRoleService.queryRoleIdList(userId);
        //用户权限列表
        Set<String> permsSet = sysMenuService.getUserPermissions(userId);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        info.setRoles(roleSet);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();

        // Null username is invalid
        if (username == null) {
            throw new AccountException("用户名不能为空！");
        }

        //查询用户信息
        SysUserEntity user = sysUserService.queryByUserName(username);

        //账号不存在
        if(user == null) {
            throw new UnknownAccountException("账户不存在");
        }

        //账号锁定
        if(user.getStatus() == 0){
            throw new LockedAccountException("该账号已经被锁定");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        return info;
    }

    public void setSysUserService(ISysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    public void setSysMenuService(ISysMenuService sysMenuService) {
        this.sysMenuService = sysMenuService;
    }

    public void setSysRoleService(ISysRoleService sysRoleService) {
        this.sysRoleService = sysRoleService;
    }


}
